package com.devplatform.service.impl.article;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devplatform.mapper.CategoriesMapper;
import com.devplatform.mapper.article.ArticleAttachmentMapper;
import com.devplatform.mapper.article.ArticleInteractionsMapper;
import com.devplatform.mapper.article.ArticleMapper;
import com.devplatform.pojo.Categories;
import com.devplatform.pojo.article.Article;
import com.devplatform.pojo.article.ArticleAttachment;
import com.devplatform.pojo.article.ArticleCategories;
import com.devplatform.pojo.dto.ArticleAttachmentDto;
import com.devplatform.pojo.dto.ArticleDetailDto;
import com.devplatform.pojo.dto.ArticleDraftDto;
import com.devplatform.pojo.dto.ArticlePublishDto;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.article.ArticleInteractionsService;
import com.devplatform.service.article.ArticleService;
import com.devplatform.service.points.PointsDetailService;
import com.devplatform.util.MessageUtil;
import com.devplatform.util.OssUtil;
import com.devplatform.util.UserContextHolder;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jnks03
 * @description 针对表【article】的数据库操作Service实现
 * @createDate 2025-09-26 16:41:04
 */
@Log4j2
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
        implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private CategoriesMapper categoriesMapper;
    @Autowired
    private ArticleAttachmentMapper attachmentMapper;
    @Autowired
    private ArticleInteractionsService articleInteractionsService;
    @Autowired
    private ArticleInteractionsMapper articleInteractionsMapper;
    @Autowired
    private PointsDetailService pointsDetailService;
    @Autowired
    private MessageUtil messageUtil;

    @Override
    public Long getAuthorIdByArticleId(Long articleId) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getArticleId, articleId);
        Article article = articleMapper.selectOne(queryWrapper);
        return article.getAuthorId();
    }

    @Override
    public DataVo saveDraft(ArticlePublishDto dto) {
        Long authorId = UserContextHolder.getUserId();
        Article article = new Article();

        // 编辑已有草稿：查询并校验权限
        if (dto.getArticleId() != null) {
            Article existingArticle = articleMapper.selectById(dto.getArticleId());
            if (existingArticle == null || !existingArticle.getAuthorId().equals(authorId)) {
                return DataVo.error("无权编辑此草稿");
            }
            article.setArticleId(dto.getArticleId());
        }

        // 填充文章基本信息
        article.setTitle(dto.getTitle());
        article.setContent(dto.getContent());
        article.setSummary(dto.getSummary());
        article.setAuthorId(authorId);
        article.setStatusId(2); // 2-草稿状态

        // 设置时间字段
        if (article.getArticleId() == null) {
            article.setCreateTime(LocalDateTime.now());
        }
        article.setUpdateTime(LocalDateTime.now());

        // 保存文章（新增或更新）
        if (article.getArticleId() == null) {
            articleMapper.insert(article);
        } else {
            articleMapper.updateById(article);
        }

        // 处理板块关联（先删后加）
        articleMapper.deleteArticleCategoriesByArticleId(article.getArticleId());
        List<ArticleCategories> categoryRelations = new ArrayList<>();
        for (Integer cateId : dto.getCategoryIds()) {
            ArticleCategories relation = new ArticleCategories();
            relation.setArticleId(article.getArticleId());
            relation.setCategoryId(cateId);
            categoryRelations.add(relation);
        }
        articleMapper.batchInsertArticleCategories(categoryRelations);

        // 处理附件（先删旧附件，再上传新附件）
        if (dto.getAttachments() != null && !dto.getAttachments().isEmpty()) {
            // 删除旧附件
            attachmentMapper.deleteByArticleId(article.getArticleId());
            // 上传新附件并保存记录
            List<ArticleAttachment> attachments = new ArrayList<>();
            for (int i = 0; i < dto.getAttachments().size(); i++) {
                MultipartFile file = (MultipartFile) dto.getAttachments().get(i);
                try {
                    String ossUrl = OssUtil.uploadFile(authorId, file);
                    ArticleAttachment attachment = new ArticleAttachment();
                    attachment.setOssUrl(ossUrl);
                    attachment.setArticleId(article.getArticleId());
                    attachments.add(attachment);
                } catch (IOException e) {
                    return DataVo.error("附件上传失败：" + file.getOriginalFilename());
                }
            }
            attachmentMapper.batchInsert(attachments);
        }

        return DataVo.ok(article.getArticleId().toString());
    }

    @Override
    public DataVo publish(Long articleId) {
        try {
            // 1. 从上下文获取当前登录用户ID（作者ID）
            Long authorId = UserContextHolder.getUserId();
            if (authorId == null) {
                return DataVo.error("请先登录");
            }

            // 2. 查询文章信息
            Article article = articleMapper.selectById(articleId);

            // 3. 权限与状态校验（核心）
            // 校验逻辑：文章存在 + 是当前用户的文章 + 状态为“草稿”（假设 statusId=0 为草稿，1为已发布）
            if (article == null) {
                return DataVo.error("文章不存在");
            }
            if (!article.getAuthorId().equals(authorId)) {
                return DataVo.error("无权限：只能发布自己的文章");
            }
            if (article.getStatusId() != 2) {
                return DataVo.error("只能发布草稿状态的文章");
            }

            article.setStatusId(1); // 已发布状态
            article.setPublishTime(LocalDateTime.now()); // 记录发布时间
            article.setUpdateTime(LocalDateTime.now()); // 更新修改时间


            articleMapper.updateById(article);
            articleInteractionsService.initArticleInteractions(articleId);
            pointsDetailService.ArticlePoints(authorId, "ARTICLE_PUBLISH");

            return DataVo.ok(articleId.toString()); // 返回发布成功的文章ID

        } catch (Exception e) {

            return DataVo.error("发布失败：" + e.getMessage());
        }
    }

    @Override
    public DataVo getDraftList(Long authorId, IPage<ArticleDraftDto> dtoIPage) {
        Page<ArticleDraftDto> page;
        if (dtoIPage instanceof Page) {
            // 如果传入的是 Page 实例，直接强转使用
            page = (Page<ArticleDraftDto>) dtoIPage;
        } else {
            // 如果传入的是其他 IPage 实现类，用其页码和条数创建 Page
            page = new Page<>(dtoIPage.getCurrent(), dtoIPage.getSize());
        }
        IPage<ArticleDraftDto> resultPage = articleMapper.selectDraftList(page, authorId);
        return DataVo.ok(resultPage);
    }

    @Override
    public DataVo deleteDraft(Long articleId, Long authorId) {
        /*Article article = articleMapper.selectById(articleId);
        if (article == null || !article.getAuthorId().equals(authorId) || article.getStatusId() != 1) {
            return DataVo.error("无权删除此草稿");
        }*/
        articleMapper.deleteById(articleId);
        articleMapper.deleteArticleCategoriesByArticleId(articleId);
        attachmentMapper.deleteByArticleId(articleId);
        return DataVo.ok();
    }

    @Override
    public DataVo getArticleDetail(Long articleId, Long authorId) {
        // 查询文章基本信息
        Article article = articleMapper.selectById(articleId);
        if (article == null || !article.getAuthorId().equals(authorId)) {
            return DataVo.error("无权查看此文章");
        }

        // 转换为详情DTO
        ArticleDetailDto detailDto = new ArticleDetailDto();
        BeanUtils.copyProperties(article, detailDto);

        // 补充板块ID列表
        List<Integer> categoryIds = articleMapper.selectCategoryIdsByArticleId(articleId);
        detailDto.setCategoryIds(categoryIds);

        // 补充附件列表
        List<ArticleAttachmentDto> attachments = attachmentMapper.selectByArticleId(articleId);
        detailDto.setAttachments(attachments);

        return DataVo.ok(detailDto);
    }

    @Override
    public List<Categories> getAllCategories() {
        return categoriesMapper.selectList(new QueryWrapper<>());
    }


}




